<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="预约时间">
        <el-date-picker
          v-model="daterangeRegistTime"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="姓名" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入姓名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="手机号码" prop="phone">
        <el-input
          v-model="queryParams.phone"
          placeholder="请输入手机号码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="预约渠道" prop="appointmentWay">
        <el-select
          v-model="queryParams.appointmentWay"
          placeholder="请选择预约渠道"
          clearable
        >
          <el-option
            v-for="dict in dict.type.user_channel_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <!--    <el-row :gutter="10" class="mb8">-->
    <!--      <el-col :span="1.5">-->
    <!--        <el-button-->
    <!--          type="success"-->
    <!--          plain-->
    <!--          icon="el-icon-edit"-->
    <!--          size="mini"-->
    <!--          :disabled="single"-->
    <!--          @click="handleUpdate"-->
    <!--          v-hasPermi="['register:yuyue:edit']"-->
    <!--        >修改-->
    <!--        </el-button>-->
    <!--      </el-col>-->
    <!--      <el-col :span="1.5">-->
    <!--        <el-button-->
    <!--          type="danger"-->
    <!--          plain-->
    <!--          icon="el-icon-delete"-->
    <!--          size="mini"-->
    <!--          :disabled="multiple"-->
    <!--          @click="handleDelete"-->
    <!--          v-hasPermi="['register:yuyue:remove']"-->
    <!--        >删除-->
    <!--        </el-button>-->
    <!--      </el-col>-->
    <!--      <el-col :span="1.5">-->
    <!--        <el-button-->
    <!--          type="warning"-->
    <!--          plain-->
    <!--          icon="el-icon-download"-->
    <!--          size="mini"-->
    <!--          @click="handleExport"-->
    <!--          v-hasPermi="['register:yuyue:export']"-->
    <!--        >导出-->
    <!--        </el-button>-->
    <!--      </el-col>-->
    <!--      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>-->
    <!--    </el-row>-->

    <el-table
      v-loading="loading"
      :data="yuyueList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="id" align="center" prop="id" />

      <el-table-column
        label="就诊卡号"
        align="center"
        width="130"
        prop="clinicCard"
      />
      <el-table-column label="姓名" align="center" prop="name" />
      <el-table-column label="年龄" align="center" prop="age" />
      <el-table-column label="性别" align="center" prop="sex">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_user_sex" :value="scope.row.sex" />
        </template>
      </el-table-column>
      <el-table-column label="图片" align="center" prop="img" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.img" :width="50" :height="50" />
        </template>
      </el-table-column>
      <el-table-column
        label="手机号码"
        align="center"
        width="130"
        prop="phone"
      />
      <el-table-column
        label="预约渠道"
        align="center"
        width="90"
        prop="appointmentWay"
      >
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.user_channel_status"
            :value="scope.row.appointmentWay"
          />
        </template>
      </el-table-column>
      <el-table-column label="预约科室" align="center" prop="department.name" />
      <el-table-column label="预约医生" align="center" prop="doctor.name" />
      <el-table-column
        fixed="right"
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        width="220"
      >
        <template slot-scope="scope">
          <!-- <el-button
            size="mini"
            type="text"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['register:yuyue:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"

            @click="toggleRegistration(scope.row)"
          >
            {{ scope.row.registStatus == 0 ? '登记' : '取消登记' }}
          </el-button>
          <el-button
            size="mini"
            type="text"
            @click="handleDelete(scope.row)"
            v-hasPermi="['register:yuyue:remove']"
          >
            {{ scope.row.del == 0 ? '作废' : '' }}
          </el-button> -->

          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleTotal(scope.row)"
            v-hasPermi="['discharge:discharge:remove']"
            >消费单</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改预约对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <!-- 第一行: 预约时间和就诊科室 -->
        <el-row :gutter="20">
          <!-- 第一行: 预约时间和就诊卡号 -->
          <el-col :span="12">
            <el-form-item label="预约时间" prop="registTime">
              <el-date-picker
                clearable
                v-model="form.registTime"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="请选择预约时间"
              />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="就诊卡号" prop="clinicCard">
              <el-input
                v-model="form.clinicCard"
                placeholder="请输入就诊卡号"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="就诊科室" prop="departmentId">
              <el-select v-model="form.departmentId" placeholder="请选择科室">
                <el-option
                  v-for="item in departmentList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                >
                  {{ item.name }}
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="就诊医生" prop="doctorId">
              <el-select v-model="form.doctorId" placeholder="请选择医生">
                <el-option
                  v-for="item in doctorList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                >
                  <span v-if="item.departmentId == form.departmentId">
                    {{ item.name }}
                  </span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第三行: 就诊姓名和就诊性别 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="姓名" prop="name">
              <el-input v-model="form.name" placeholder="请输入姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="性别" prop="sex">
              <el-radio-group v-model="form.sex">
                <el-radio
                  v-for="dict in dict.type.sys_user_sex"
                  :key="dict.value"
                  :label="dict.value"
                  >{{ dict.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第四行: 身份证号和就诊年龄 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="身份证号" prop="identityCard">
              <el-input
                v-model="form.identityCard"
                placeholder="请输入身份证号"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="年龄" prop="age">
              <el-input-number
                v-model="form.age"
                controls-position="right"
                :min="0"
                :max="150"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第五行: 手机号码和所属民族 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="手机号码" prop="phone">
              <el-input v-model="form.phone" placeholder="请输入手机号码" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属民族" prop="nation">
              <el-select
                v-model="form.nation"
                placeholder="请选择所属民族"
                clearable
              >
                <el-option
                  v-for="dict in dict.type.people_ethnic_ffiliation"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第六行: 联系地址 -->
        <el-form-item label="联系地址" prop="address">
          <el-input v-model="form.address" placeholder="请输入联系地址" />
        </el-form-item>
        <el-form-item label="预约渠道" prop="appointmentWay">
          <el-radio-group v-model="form.appointmentWay">
            <el-radio
              v-for="dict in dict.type.user_channel_status"
              :key="dict.value"
              :label="dict.value"
            >
              {{ dict.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="图片" prop="picture">
          <image-upload v-model="form.img" />
        </el-form-item>

        <!-- 第七行: 门诊编号和住院编号 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="门诊编号" prop="outpatientId">
              <el-input
                v-model="form.outpatientId"
                placeholder="请输入门诊编号"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="住院编号" prop="admissionId">
              <el-input
                v-model="form.admissionId"
                placeholder="请输入住院编号"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第八行: 医保性质和医保卡号 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="医保性质" prop="nature">
              <el-input v-model="form.nature" placeholder="请输入医保性质" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="医保卡号" prop="cardnumber">
              <el-input
                v-model="form.cardnumber"
                placeholder="请输入医保卡号"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align: center">
        <el-button type="primary" @click="submitForm">保存挂号</el-button>
      </div>
    </el-dialog>

    <el-dialog
      :title="fullDialogTitle()"
      :visible.sync="dialogVisible"
      width="50%"
    >
      <div class="custom-descriptions-container">
        <div class="custom-descriptions-item">
          <span class="label">挂号费用：</span>
          <span class="value" v-if="totalForm.registerCost !== ''"
            >{{ costDetail[totalForm.registerCost] }}元</span
          >
          <span class="label" v-else>无</span>
        </div>
        <div class="custom-descriptions-item">
          <span class="label">问诊费用：</span>
          <span class="value" v-if="totalForm.interrogationCost !== ''"
            >{{ costDetail[totalForm.interrogationCost] }}元</span
          >
          <span class="label" v-else>无</span>
        </div>
        <div class="custom-descriptions-item">
          <span class="label">药品费用：</span>
          <span class="value" v-if="totalForm.medicalCost !== ''"
            >{{ costDetail[totalForm.medicalCost] }}元</span
          >
          <span class="label" v-else>无</span>
        </div>
        <div class="custom-descriptions-item">
          <span class="label">病房费用：</span>
          <span class="value" v-if="totalForm.wardCost !== ''"
            >{{ costDetail[totalForm.wardCost] }}元</span
          >
          <span class="label" v-else>无</span>
        </div>
        <div class="custom-descriptions-item">
          <span class="label">检查费用：</span>
          <span class="value" v-if="totalForm.inspectionCost !== ''"
            >{{ costDetail[totalForm.inspectionCost] }}元</span
          >
          <span class="label" v-else>无</span>
        </div>
        <div class="custom-descriptions-item">
          <span class="label">总费用：</span>
          <span class="value">{{ patientCurrentMoney }}元</span>
        </div>
        <!-- 其他费用项类似 -->
        <div>
          <el-button type="primary" @click="goPay" v-if="isPay == false"
            >去支付</el-button
          >
          <el-button type="success" v-else>已支付</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listYuyue,
  getYuyue,
  delYuyue,
  addYuyue,
  updateYuyue,
  getDepartmentList,
  getDoctorList,
  delCostByParentId,
  delConsultationByRegisterId,
} from "@/api/register/yuyue";
// 	引入支付
import { pay, ispay } from "@/api/discharge/pay";
import { listCost } from "@/api/cost/cost";

export default {
  name: "Yuyue",
  dicts: [
    "people_ethnic_ffiliation",
    "user_channel_status",
    "sys_yes_no",
    "sys_user_sex",
  ],
  data() {
    return {
      doctorList: [],
      departmentList: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 预约表格数据
      yuyueList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 预约医生时间范围
      daterangeRegistTime: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        registTime: null,
        name: null,
        phone: null,
        isCancel: null,
        appointmentWay: null,
        departmentId: null,
      },
      // 表单参数
      form: {},
      dialogVisible: false, //	控制消费单显示隐藏
      totalForm: {
        registerCost: "",
        interrogationCost: "",
        medicalCost: "",
        wardCost: "",
        inspectionCost: "",
      },
      currentName: "",
      dialogTitle: "消费单详情", // 初始标题
      patientCurrentId: "",
      patientCurrentMoney: 0, //	当前消费单的金额
      costDetail: [],
      isPay: false, //	是否已付费

      // 表单校验
      rules: {
        registTime: [
          { required: true, message: "预约时间不能为空", trigger: "blur" },
        ],
        department: [
          { required: true, message: "就诊科室不能为空", trigger: "change" },
        ],
        doctorId: [
          { required: true, message: "就诊医生不能为空", trigger: "change" },
        ],
        clinicCard: [
          { required: true, message: "就诊卡号不能为空", trigger: "blur" },
        ],
        name: [{ required: true, message: "姓名不能为空", trigger: "blur" }],
        identityCard: [
          { required: true, message: "身份证号不能为空", trigger: "blur" },
        ],
        age: [{ required: true, message: "年龄不能为空", trigger: "blur" }],
        sex: [{ required: true, message: "性别不能为空", trigger: "change" }],
        phone: [
          { required: true, message: "手机号码不能为空", trigger: "blur" },
        ],
        nation: [
          { required: true, message: "民族不能为空", trigger: "change" },
        ],
        address: [
          { required: true, message: "联系地址不能为空", trigger: "blur" },
        ],
        appointmentWay: [
          { required: true, message: "预约渠道不能为空", trigger: "change" },
        ],
        departmentId: [
          { required: true, message: "预约科室不能为空", trigger: "change" },
        ],
      },
    };
  },
  created() {
    this.getList();
    this.getDepartmentList();
    this.getDoctorList();
  },

  methods: {
    //	去支付的方法
    goPay() {
      pay(this.patientCurrentId, this.patientCurrentMoney)
        .then((res) => {
          var payGatewayHtml = res; // 假设这是返回的HTML表单字符串

          // 创建一个新的窗口（或标签页）
          var newWindow = window.open("", "_blank");

          // 如果新窗口被阻止，则处理错误情况
          if (
            !newWindow ||
            newWindow.closed ||
            typeof newWindow.closed == "undefined"
          ) {
            alert("新窗口被阻止，请允许弹出窗口以继续支付。");
            return;
          }

          // 写入表单HTML到新窗口的文档中
          newWindow.document.write(payGatewayHtml);

          // 由于document.write是同步的，我们可以立即关闭写入流
          newWindow.document.close();

          // 注意：通常不需要手动提交表单，因为表单HTML可能已经包含了自动提交的逻辑（如onsubmit事件）
          // 如果需要手动提交，并且表单有唯一的ID或可以通过其他方式选择，你可以在新窗口的文档中查找并提交它
          // 例如：var form = newWindow.document.getElementById('paymentForm'); form.submit();
          // 但这通常不是必需的，除非支付网关有特定的要求
        })
        .catch((error) => {
          console.error("支付请求失败:", error);
        });
    },

    fullDialogTitle() {
      return `${this.dialogTitle} - ${this.currentName}`;
    },
    // 消费单按钮操作
    handleTotal(row) {
      this.reset();
      this.currentName = row.name;
      this.loading = true;
      let query = {
        patientId: "",
      };
      //	获取当前患者id用作付费商品单号，金额用作转账额度
      query.patientId = row.id;
      this.patientCurrentId = row.id;
      // this.patientCurrentMoney = row.costTotal

      //	判断是否已经付过钱
      ispay(this.patientCurrentId).then((response) => {
        if (response == "10000") {
          console.log(response);
          this.isPay = true;
          console.log(this.isPay);
        } else {
          console.log("还没付过钱");
        }
      });

      listCost(query).then((response) => {
        // this.totalForm = response.rows
        // console.log(this.totalForm);
        for (var i = 0; i < response.rows.length; i++) {
          this.$set(
            this.costDetail,
            response.rows[i].costType,
            response.rows[i].money
          ); //	放入费用类型和金额到键值对数组中
          // console.log(response.rows[i].costType+":"+response.rows[i].money);
          if (response.rows[i].costType == "0") {
            this.totalForm.registerCost = response.rows[i].costType;
          } else if (response.rows[i].costType == "1") {
            this.totalForm.interrogationCost = response.rows[i].costType;
          } else if (response.rows[i].costType == "2") {
            this.totalForm.medicalCost = response.rows[i].costType;
          } else if (response.rows[i].costType == "3") {
            this.totalForm.wardCost = response.rows[i].costType;
          } else if (response.rows[i].costType == "4") {
            this.totalForm.inspectionCost = response.rows[i].costType;
          }
          this.patientCurrentMoney += +response.rows[i].money;
        }
        // console.log(this.costDetail);
      });
      this.loading = false;
      this.dialogVisible = true;
    },

    toggleRegistration(row) {
      const newStatus = row.registStatus == 0 ? 1 : 0;
      this.updateRegistrationStatus(row.id, newStatus)
        .then(() => {
          // 这里我们在数据库更新成功后才改变 UI 状态
          row.registStatus = newStatus; // 更新表格中的数据
        })
        .catch(() => {
          this.$modal.msgError("操作失败");
        });
    },

    // 更新预约状态
    updateRegistrationStatus(id, registStatus) {
      return updateYuyue({ id, registStatus })
        .then((response) => {
          // this.$modal.msgSuccess(registStatus == 1 ? "登记成功" : "取消登记成功");
          // this.getList(); // 刷新表格数据
        })
        .catch(() => {
          this.$modal.msgError("操作失败");
        });
    },
    getDoctorList() {
      getDoctorList().then((response) => {
        this.doctorList = response.rows;
      });
    },
    getDepartmentList() {
      getDepartmentList().then((response) => {
        this.departmentList = response.rows;
      });
    },
    /** 查询预约列表 */
    getList() {
      this.loading = true;
      this.queryParams.params = {};
      if (null != this.daterangeRegistTime && "" != this.daterangeRegistTime) {
        this.queryParams.params["beginRegistTime"] =
          this.daterangeRegistTime[0];
        this.queryParams.params["endRegistTime"] = this.daterangeRegistTime[1];
      }
      listYuyue(this.queryParams).then((response) => {
        this.yuyueList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        registStatus: null,
        registTime: null,
        clinicCard: null,
        name: null,
        identityCard: null,
        age: null,
        sex: null,
        img: null,
        phone: null,
        nation: null,
        address: null,
        outpatientId: null,
        medicalhistory: null,
        admissionId: null,
        nature: null,
        cardnumber: null,
        isCancel: null,
        medicalFee: null,
        appointmentWay: null,
        departmentId: null,
        doctorId: null,
        del: null,
      };
      this.resetForm("form");
      this.totalForm = {
        registerCost: "",
        interrogationCost: "",
        medicalCost: "",
        wardCost: "",
        inspectionCost: "",
      };
      this.currentName = "";
      this.patientCurrentId = "";
      this.patientCurrentMoney = 0; //	当前消费单的金额
      this.costDetail = [];
      this.isPay = false; //	是否已付费
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
      this.getDepartmentList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeRegistTime = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加预约";
      this.getDepartmentList();
      this.getDoctorList();
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getYuyue(id).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改预约";
        this.getDepartmentList();
        this.getDoctorList();
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateYuyue(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addYuyue(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认作废预约编号为"' + ids + '"的数据项？,此结果不可逆!')
        .then(function () {
          return delYuyue(ids)
            .then(() => delCostByParentId(ids))
            .then(() => delConsultationByRegisterId(ids));
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("作废成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "register/yuyue/export",
        {
          ...this.queryParams,
        },
        `yuyue_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>

<style>
.custom-descriptions-container {
  display: flex;
  flex-direction: column; /* 垂直布局 */
  align-items: stretch; /* 确保子项填满容器 */
}

.custom-descriptions-item {
  display: flex;
  justify-content: space-between; /* 水平对齐，两端对齐 */
  padding: 15px 0; /* 上下内边距 */
  border-bottom: 1px solid #ebeef5; /* 可选，添加分隔线 */
}
.custom-descriptions-item:last-child {
  border-bottom: none; /* 移除最后一个子项的分隔线 */
}

.label {
  flex: 1; /* 占据剩余空间的一部分 */
  font-weight: bold; /* 加粗 */
  margin-right: 20px; /* 与值之间添加间距 */
}

.value {
  flex: 2; /* 占据剩余空间的大部分 */
  font-size: 16px; /* 调整字体大小 */
}
</style>
